/*
 * @Author: Ben Fang
 * @Date: 2022-06-02 10:18:42
 * @LastEditors: Ben Fang
 * @LastEditTime: 2022-06-06 08:14:29
 */
const gm = require("gm");
const fs = require("fs");
/**
 * 删除文件夹下所有文件
 * @param {string} path 文件夹路径
 */
function delDir(path) {
  let files = [];
  if (fs.existsSync(path)) {
    files = fs.readdirSync(path);
    files.forEach((file, index) => {
      let curPath = path + "/" + file;
      if (fs.statSync(curPath).isDirectory()) {
        delDir(curPath); //递归删除文件夹
      } else {
        fs.unlinkSync(curPath); //删除文件
      }
    });
  }
}

/**
 * 合并图片
 * @param {string} savepath 生成图片保存路径，linux下绝对路径加文件名
 */
module.exports.convertImage = (savepath) => {
  const path = "./images";
  const fileList = fs.readdirSync(path);
  let all = gm(`${path}/${fileList[0]}`);
  fileList.forEach((element, index) => {
    if (index > 0) {
      all.append(`${path}/${fileList[index]}`);
    }
  });
  all.write(savepath, (err) => {
    if (err) console.log(err);
    delDir(path);
  });
};
